import React, { Component } from 'react';
import { Button, List, SearchBar, Toast, WingBlank } from 'antd-mobile';
import { Image, ScrollView, StatusBar, Text, TouchableWithoutFeedback, View } from 'react-native';
import styles from './style';
const Item = List.Item;

export default class extends Component {
  constructor(props) {
    super(props);
    this.state = {
      hotwords: '',
      keywords: '',
      list: [],
    };
    this.renderHotWords = this.renderHotWords.bind(this);
    this.changeKeyWords = this.changeKeyWords.bind(this);
    this.goSearch = this.goSearch.bind(this);
  }

  static navigationOptions = ({ navigation }) => ({
    title: '搜索',
    headerBackTitle: null,
    headerTitleStyle: {
      color: '#fff',
    },
    headerStyle: {
      backgroundColor: '#ed4040'
    },
    tabBarLabel: '搜索',
    headerLeft: (
      <TouchableWithoutFeedback onPress={() => {
        Toast.hide();
        navigation.goBack();
      }}>
          <View>
            <Image style={{ width: 23, height: 23, tintColor: '#fff', marginLeft: 10 }}
                   source={require('../../images/back.png')}
                   resizeMode="cover"
            />
          </View>
        </TouchableWithoutFeedback>
    ),
    tabBarIcon: ({ tintColor }) => (
      <Image
        source={require('../../images/search.png')}
        style={[styles.icon, { tintColor: tintColor }]}
      />
    ),
  });

  async componentDidMount() {
    Toast.loading('加载中...', 999999999999);
    let f = await fetch('https://ecmad.com/toutiao/api/system/keywords', {
      method: 'GET',
    }).catch(() => {
      Toast.offline('网络异常', 2, f => f, false);
    });
    let res = await f.json();
    if (res.code === 200) {
      Toast.hide();
      this.setState({
        hotwords: res.data[0].content,
      });
    } else {
      Toast.offline('网络异常', 2, f => f, false);
    }
  }

  changeKeyWords(val) {
    this.setState({
      keywords: val,
    });
  }

  /**
   * 搜索
   * @param input
   * @returns {Promise.<boolean>}
   */
  async goSearch(input) {
    let keywords = '';
    if (input) {
      keywords = input;
      this.setState({
        keywords,
      });
    } else {
      keywords = this.state.keywords;
      if (!keywords) {
        Toast.info('请输入关键词', 2, f => f, false);
        this.setState({
          list: [],
        });
        return false;
      }
    }
    Toast.loading('加载中...', 999999999999);
    let f = await fetch(`https://ecmad.com/toutiao/api/article/search?keywords=${keywords.replace(/\s/img, ',')}`, {
      method: 'GET',
    }).catch(() => {
      Toast.offline('网络异常', 2, f => f, false);
    });
    let res = await f.json();
    if (res.code === 200) {
      Toast.hide();
      this.setState({
        list: res.data,
      });
    } else {
      Toast.offline('网络异常', 2, f => f, false);
    }
  }

  renderHotWords() {
    const { hotwords } = this.state;
    return hotwords.split(/,|，|\n+/img).filter(v => v).map((item, index) => (
      <Button
        size="small"
        style={styles.tags}
        key={index}
        onClick={() => this.goSearch(item)}
      >
        <Text style={{ fontSize: 13, color: '#666' }}>{item}</Text>
      </Button>
    ))
  }

  renderPureText(item = {}) {
    const { navigate } = this.props.navigation;
    return (
      <Item
        multipleLine
        align="top"
        wrap
        onClick={() => navigate('Detail', {
          title: item.title,
          id: item.id,
        })} key={item.id}
        style={styles.listItem}
      >
        <Text style={styles.listTitle}>{item.title}</Text>
        <View style={styles.listInfo}>
          <Text style={styles.ListText}>{item.public_name}</Text>
          <Text style={styles.ListText}>{item.datetime}</Text>
        </View>
      </Item>
    );
  }

  renderOnePicText(item = {}) {
    const { navigate } = this.props.navigation;
    return (
      <Item
        extra={<Image source={{ uri: item.images[0] }} style={styles.cover} />}
        multipleLine
        align="top"
        wrap
        onClick={() => navigate('Detail', {
          title: item.title,
          id: item.id,
        })} key={item.id}
        style={styles.listItem}
      >
        <Text style={styles.listTitle}>{item.title}</Text>
        <View style={styles.listInfo}>
          <Text style={styles.ListText}>{item.public_name}</Text>
          <Text style={styles.ListText}>{item.datetime}</Text>
        </View>
      </Item>
    );
  }

  renderThreePicText(item = {}) {
    const { navigate } = this.props.navigation;
    return (
      <Item
        multipleLine
        align="top"
        wrap
        onClick={() => navigate('Detail', {
          title: item.title,
          id: item.id,
        })} key={item.id}
        style={styles.listItem}
      >
        <Text style={styles.listTitle}>{item.title}</Text>
        <View style={styles.listImages}>
          <Image source={{ uri: item.images[0] }} style={styles.listImageCell} />
          <View style={{ width: 5 }}></View>
          <Image source={{ uri: item.images[1] }} style={styles.listImageCell} />
          <View style={{ width: 5 }}></View>
          <Image source={{ uri: item.images[2] }} style={styles.listImageCell} />
        </View>
        <View style={styles.listInfo}>
          <Text style={styles.ListText}>{item.public_name}</Text>
          <Text style={styles.ListText}>{item.datetime}</Text>
        </View>
      </Item>
    );
  }

  render() {
    const { keywords, list } = this.state;
    return (
      <ScrollView style={styles.search}>
        <StatusBar barStyle="light-content" />
        <WingBlank size="sm">
          <SearchBar
            placeholder="请输入关键词"
            value={keywords}
            maxLength={20}
            onChange={this.changeKeyWords}
            onSubmit={this.goSearch}
          />
          <View style={styles.tagsContainer}>
            <Text style={styles.hotwords}>热门</Text>{this.renderHotWords()}
          </View>
          <List style={styles.list}>
          {
            Array.isArray(list) && list.map(item => {
              if (item.images.length === 0) {
                return this.renderPureText(item)
              } else if (item.images.length > 0 && item.images.length < 3) {
                return this.renderOnePicText(item)
              } else if (item.images.length >= 3) {
                return this.renderThreePicText(item)
              }
            })
          }
        </List>
        </WingBlank>
      </ScrollView>
    );
  }
}
